package api

import (
	"github.com/gin-gonic/gin"
	"hub.hddznet.com/app/framework/service/mgo"
	"hub.hddznet.com/app/framework/action"
	"gopkg.in/mgo.v2/bson"
	"hub.hddznet.com/app/framework/errs"
	"net/http"
	"io"
	"bytes"
	"fmt"
)

var db = new(mgo.Mongo)

func (this *scada6) initDB() {
	if db.Fs == nil {
		mgo.InitMongoWithoutRegist(db)
	}
}

func (this *scada6) UploadPost(r *gin.RouterGroup, path, formfile string) {
	this.initDB()
	r.POST(path, func(c *gin.Context) {
		action.Do(c, nil, 0, func() (interface{}, error) {
			file, header, err := c.Request.FormFile(formfile)
			if err != nil {
				return nil, errs.FsGetErr(err.Error())
			}
			url, err := db.Fs.HDUploadScada6(header.Filename, header.Header.Get("Content-Type"), file)
			db.Fs.Files.UpsertId(url, bson.M{"$set": bson.M{"mime": header.Header.Get("Content-Type")}})
			if err != nil {
				return nil, err
			}
			return bson.M{"url": url}, nil
		})
	})
}

func (this *scada6) UploadGet(r *gin.RouterGroup) {
	this.initDB()
	r.GET("/upload/*action", func(c *gin.Context) {
		fmt.Println(c.Request.URL.String())

		data, err := db.Fs.HDGet(c.Request.URL.String())
		if err != nil {
			c.Data(http.StatusNotFound, "", nil)
			return
		}
		io.Copy(c.Writer, bytes.NewReader(data))
	})
}

type scada6 struct{}

var Scada6 *scada6

func init() {
	Scada6 = new(scada6)
}
